# -*-coding:utf-8 -*-
from datetime import datetime
from ..xz_handler.gps_mongo import GPSMongoHandler


class KYGPSMongoHandler(GPSMongoHandler):

    def format_gps(self, data):
        speed = int(data['speed'])
        speed = round(speed * 60 * 60 / 100 / 1000, 23) if speed != 0 else 0
        doc = {
            'longitude':  float(data['longtitude']),
            'latitude':  float(data['latitude']),
            'direction':  float(data['heading']),
            'altitude': float(data['altitude']),
            'speed': speed,
            'occurred_time': datetime.fromtimestamp(int(data['time'])),
        }
        return doc

    def handle(self, msg, license_number):
        start_timespan = datetime.fromtimestamp(int(msg['time']))
        start_timespan = self._get_start_timespan(start_timespan)
        device_imei = msg['deviceId']
        set_on_insert = {
            'start_timespan': start_timespan,
            'device_imei': device_imei,
            "vehicle_license_number": license_number,
            "meta": {
                "version": 0.1,
                "provider": "kaiyi"
            },
            'created_time': datetime.now(),
        }
        collection = self._get_collection_name(start_timespan)
        self.db[collection].update_one(
            {'start_timespan': start_timespan, 'device_imei': device_imei},
            {
                '$setOnInsert': set_on_insert,
                '$inc': {'gps_count': 1},
                '$push': {'gps': self.format_gps(msg)}
            },
            upsert=True,
        )
